package com.tcat.item.aop;

import com.tcat.common.exception.TcatException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 日志的Aop切面
 * 控制台输出请求的相关参数，及响应结果
 */
@Aspect
@Slf4j
@Component
public class WebLog {
    @Pointcut("execution(* com.tcat.item.web..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint)throws Throwable{
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes != null){
            HttpServletRequest request = attributes.getRequest();
            log.info("==========");
            log.info("Cookie:"+ request.getHeader("Cookie"));
            log.info(request.getMethod()+"=>"+request.getRequestURL().toString());
            log.info("IP:"+request.getRemoteAddr());
            log.info("CLASS_METHOD:"+joinPoint.getSignature().getDeclaringTypeName()
            +"."
            +joinPoint.getSignature().getName());
            log.info("ARGS:"+ Arrays.toString(joinPoint.getArgs()));
            log.info("=============\n");
        }
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret)throws Throwable{
        log.info("RESPONSE:"+ret);
        log.info("==========\n");
    }

    @AfterThrowing(throwing = "error", pointcut = "webLog()")
    public void doAfterThrowing(TcatException error){
        log.error("{},code={}",error.getExceptionEnum().getMsg(),error.getExceptionEnum().getCode());
    }
}
